package com.heima.article.service.impl;

import com.heima.article.service.ApCollectionService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 霍森彪
 * @date 2022/7/28 15:29
 */
@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        Integer userId = user.getId();
        if (userId == null || userId == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //获取操作类型:收藏/取消收藏
        Short operation = dto.getOperation();
        if (operation == 0){
            //收藏逻辑
            //判断是是否已经收藏
            String collectionCount = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getEntryId(), userId.toString());
            if (StringUtils.isNotEmpty(collectionCount)){
                //说明已经收藏过,返回
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"文章已经收藏过了");
            }
            //否则添加收藏记录
            Long currentTimeMillis = System.currentTimeMillis();
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR+dto.getEntryId(),userId.toString(),currentTimeMillis.toString());
        }else{
            //取消收藏逻辑
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR+dto.getEntryId(),userId.toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
